using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using NETL.Data.Context;

namespace NETL.Engine.Context
{
	public class ExecutionContext
	{
		private static ExecutionContext myInstance = new ExecutionContext();

		public static ExecutionContext Instance()
		{
			return myInstance;
		}

		private IList<Pipeline> myPipelines;
		private ILog myLogger = LogManager.GetLogger(typeof(ExecutionContext));
		private WorkflowRuntime myWorkflowRuntime;

		public WorkflowRuntime WorkflowRuntime
		{
			get { return myWorkflowRuntime; }
			set { myWorkflowRuntime = value; }
		}

		private ExecutionContext()
		{
		}

		public void Start()
		{
			myLogger.Debug("Starting");

			myWorkflowRuntime = new WorkflowRuntime();
//			myWorkflowRuntime.AddService(new SqlWorkflowPersistenceService());
			myWorkflowRuntime.WorkflowCompleted += new EventHandler<WorkflowCompletedEventArgs>(myWorkflowRuntime_WorkflowCompleted);
			myWorkflowRuntime.WorkflowTerminated += new EventHandler<WorkflowTerminatedEventArgs>(myWorkflowRuntime_WorkflowTerminated);
			myWorkflowRuntime.WorkflowCreated += new EventHandler<WorkflowEventArgs>(myWorkflowRuntime_WorkflowCreated);
			myWorkflowRuntime.StartRuntime();

			myPipelines = new PipelineFactory().GetActivePipelines();

			foreach (Pipeline p in myPipelines)
			{
				p.Start();
			}

			myLogger.Info("Started");
		}

		void myWorkflowRuntime_WorkflowCreated(object sender, WorkflowEventArgs e)
		{
			// Mark to be stored

			throw new NotImplementedException();
		}

		void myWorkflowRuntime_WorkflowTerminated(object sender, WorkflowTerminatedEventArgs e)
		{
			throw new NotImplementedException();
		}

		void myWorkflowRuntime_WorkflowCompleted(object sender, WorkflowCompletedEventArgs e)
		{
			throw new NotImplementedException();
		}

		public void Stop()
		{
			myLogger.Debug("Stopping");

			foreach (Pipeline p in myPipelines)
			{
				p.Stop();
			}

			foreach (WorkflowInstance wfi in myWorkflowRuntime.GetLoadedWorkflows())
			{
				wfi.Unload();
			}

			myWorkflowRuntime.StopRuntime();
			myWorkflowRuntime.Dispose();
			myLogger.Info("Stopped");
		}
	}
}
